from peewee import *
from src.models.BaseModel import BaseModel
from src.util.Model2Dict import m2d
from src.entry.Entrys import Page

""" 角色表 """


class Msg(BaseModel):
    id = BigIntegerField(primary_key=True)
    title = CharField()
    msg = CharField()
    time = DateTimeField()
    send = CharField()
    type = CharField()
    room = CharField()
    status = CharField()

    # 设置模型对应的数据库表名
    class Meta:
        table_name = 'sys_msg'

    # 获取公告记录
    @staticmethod
    def getMsg(page: Page = Page(), cdn: dict = None):
        if cdn is None:
            cdn = dict()
        q = Msg.select()

        if cdn.get('send'):
            q = q.where(Msg.send == cdn.get('send'))
        if cdn.get('status'):
            q = q.where(Msg.status == cdn.get('status'))
        # 赛选标题
        if cdn.get('title'):
            q = q.where(Msg.title.contains(cdn.get('title')))
        # 筛选时间
        if cdn.get('time'):
            t: list[str] = cdn.get('time')
            if t[0]:
                q = q.where(Msg.time > t[0])
            if t[1]:
                q = q.where(Msg.time < t[1])
        # 按时间排序
        if cdn.get('order'):
            order: dict = cdn.get('order')
            if order.get('time') and order.get('time') == 'asc':
                q = q.order_by(Msg.time.asc())
            if order.get('time') and order.get('time') == 'desc':
                q = q.order_by(Msg.time.desc())
        r = q.paginate(page.num, page.size).dicts()
        page.count = q.count()
        page.rows = m2d(r)
        return page.__dict__

    # 删除记录
    @staticmethod
    def delMsg(ids: list[int]):
        Msg.delete().where(Msg.id.in_(ids)).execute()
        return True

    # 添加消息
    @staticmethod
    def addMsg(data: dict):
        Msg.insert(data).execute()
        return True

    # 更新数据
    @staticmethod
    def updateMsg(ids: list[int], data: dict):
        Msg.update(data).where(Msg.id.in_(ids)).execute()
        return True
